<template>
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button type="primary" @click="$emit('create')">
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('searchTable.operation.create') }}
        </a-button>
        <a-upload action="/" @change="$emit('import', $event)">
          <template #upload-button>
            <a-button>
              {{ $t('searchTable.operation.import') }}
            </a-button>
          </template>
        </a-upload>
      </a-space>
    </a-col>
    <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
      <a-button @click="$emit('download')">
        <template #icon>
          <icon-download />
        </template>
        {{ $t('searchTable.operation.download') }}
      </a-button>
      <a-tooltip :content="$t('searchTable.actions.refresh')">
        <div class="action-icon" @click="$emit('refresh')">
          <icon-refresh size="18" />
        </div>
      </a-tooltip>
      <a-dropdown @select="handleSelectDensity">
        <a-tooltip :content="$t('searchTable.actions.density')">
          <div class="action-icon">
            <icon-line-height size="18" />
          </div>
        </a-tooltip>
        <template #content>
          <a-doption v-for="item in densityList" :key="item.value" :value="item.value" :class="{ active: item.value === size }">
            <span>{{ item.name }}</span>
          </a-doption>
        </template>
      </a-dropdown>
      <a-tooltip :content="$t('searchTable.actions.columnSetting')">
        <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
          <div class="action-icon">
            <icon-settings size="18" />
          </div>
          <template #content>
            <div id="tableSetting">
              <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                <div style="margin-right: 4px; cursor: move">
                  <icon-drag-arrow />
                </div>
                <div>
                  <a-checkbox v-model="item.checked" @change="handleChange($event, item, index)"></a-checkbox>
                </div>
                <div class="title">
                  {{ item.title === '#' ? '序列号' : item.title }}
                </div>
              </div>
            </div>
          </template>
        </a-popover>
      </a-tooltip>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
import { computed, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import Sortable from 'sortablejs'
import cloneDeep from 'lodash/cloneDeep'

type SizeProps = 'mini' | 'small' | 'medium' | 'large'
type Column = TableColumnData & { checked?: true }

const { t } = useI18n()

// 定义组件属性
const props = defineProps<{
  size: SizeProps
  showColumns: Column[]
  cloneColumns: Column[]
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:size', value: SizeProps): void
  (e: 'update:cloneColumns', value: Column[]): void
  (e: 'update:showColumns', value: Column[]): void
  (e: 'create'): void
  (e: 'import', event: any): void
  (e: 'download'): void
  (e: 'refresh'): void
}>()

// 表格密度选项
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'),
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),
    value: 'large',
  },
])

// 处理表格密度选择
const handleSelectDensity = (val: string | number | Record<string, any> | undefined) => {
  emit('update:size', val as SizeProps)
}

// 处理列显示变更
const handleChange = (checked: boolean | (string | boolean | number)[], column: Column, index: number) => {
  const newCloneColumns = [...props.cloneColumns]
  if (!checked) {
    emit(
      'update:cloneColumns',
      newCloneColumns.filter((item) => item.dataIndex !== column.dataIndex)
    )
  } else {
    newCloneColumns.splice(index, 0, column)
    emit('update:cloneColumns', newCloneColumns)
  }
}

// 交换数组元素位置的辅助函数
const exchangeArray = <T extends Array<any>>(array: T, beforeIdx: number, newIdx: number, isDeep = false): T => {
  const newArray = isDeep ? cloneDeep(array) : array
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop())
  }
  return newArray
}

// 处理列设置弹出框可见性变化
const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e
          const newCloneColumns = exchangeArray([...props.cloneColumns], oldIndex, newIndex)
          const newShowColumns = exchangeArray([...props.showColumns], oldIndex, newIndex)
          emit('update:cloneColumns', newCloneColumns)
          emit('update:showColumns', newShowColumns)
        },
      })
    })
  }
}
</script>

<style scoped lang="less">
@import '../styles/common.less';

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>
